from rest_framework.serializers import *
from apps.users.models import *


class AdminSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        # fields = ['id', 'username', 'email', 'mobile']
        # 更新需要添加额外字段属性
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        # 1.先获取创建有问题的user
        # user = User.objects.create_user(**validated_data)
        user = super().create(validated_data)
        # 2.添加 is_staff  设置密码
        user.is_staff = True
        # 默认密码是不加密的
        user.set_password(validated_data.get('password'))
        user.save()
        return user

    def update(self, instance, validated_data):
        # 1 先让父类调用更新的数据(可以说是获取更新数据,并更新)
        instance = super().update(instance, validated_data)
        # 2 更新后判断并保存
        if validated_data.get('password'):
            instance.set_password(validated_data.get('password'))
            instance.save()
        return instance
